/*!
* @Author: luoob
* @Date: 2021-03-23 09:30:00
* @Last Modified by: luoob
* @Last Modified time: 2021-03-23 09:30:00
* @Instruduction: 中间件处理器(目前仅支持同步)
*/

import { middleware } from 'src/types/middleware'

class AppMiddleware {
    private middleware: middleware[]

    constructor() {
        this.middleware = []
    }

    /**
     * 注册中间件
     * @date 2021-03-23
     * @param {(ctx, callback)} fn
     * @returns {any}
     */
    use(fn: middleware) {
        if (typeof fn !== 'function') {
            throw new Error('middleware use: expect a function')
        }
        this.middleware.push(fn)
    }

    /**
     * 归并中间件
     * @date 2021-03-23
     * @returns {any}
     */
    compose() {
        return this.middleware.reduce((a, b) => (ctx, next) => a(ctx, () => b(ctx, next)))
    }
}

export default new AppMiddleware()
